import React from 'react';
import { Badge, Radio, Button, Popconfirm,Checkbox } from 'antd';
import { messages } from 'share/common';
import Selector from 'components/selector';
import components from 'containers/expense-reimbursement-control/new-mileage-subsidy/components';

const editableChild = [
  { name: messages('expense-12.key70')/*允许*/, value: true },
  { name: messages('expense-12.key71')/*不允许*/, value: false }
];

const manyInvoiceChild = [
  { name: messages('expense-12.key72')/*一次*/, value: '1' },
  { name: messages('expense-12.key73')/*多次*/, value: '2' }
];

export const drivingPlanValueChild = [
  { name: messages('expense-12.key74')/*智能推荐*/, value: 10 },
  { name: messages('expense-12.key75')/*时间最短*/, value: 0 },
  { name: messages('expense-12.key76')/*路程最短*/, value: 2 },
  { name: messages('expense-12.key77')/*躲避拥堵*/, value: 4 },
  { name: messages('expense-12.key78')/*员工选择策略*/, value: -1 }
];
export const mileageCreateModesValues = [
  { label: messages('expense-12.key39')/*定位创建*/, value: 'POSITIONING'},
  { label: messages('expense-12.key79')/*导航创建（仅APP端支持）*/, value: 'NAVIGATION'}
];

const drivingExtra = [
  messages('expense-12.key80')/*智能推荐：躲避拥堵，路程较短，尽量缩短时间，与导航的默认策略一致*/,
  messages('expense-12.key81')/*时间最短：速度优先，此路线不一定距离最短*/,
  messages('expense-12.key82')/*距离最短：距离优先，可能存在穿越小路/小区的情况进行计算*/,
  messages('expense-12.key83')/*躲避拥堵：可能存在绕路的情况，耗时可能较长*/,
  messages('expense-12.key84')/*员工选择策略：员工在创建里程时，可选择驾车策略，基于选择的驾车策略返回参考里程值*/
];
const mileageUnitChild = [
  { name: messages('expense-12.key85')/*公里*/, value: 'KM' },
  { name: messages('expense-12.key86')/*英里*/, value: 'MI' }
];

const levelCodeMap = {
  'TENANT': messages('expense-12.key87')/*租户*/,
  'SET_OF_BOOK': messages('expense-12.key88')/*账套*/,
  'COMPANY': messages('expense-12.key89')/*公司*/
};

const defaultMileageValue = [
  { name: messages('expense-12.key29')/*参考里程*/, value: 'reference' },
  { name: messages('expense-12.key28')/*行驶里程*/, value: 'travel' },
  { name: messages('expense-12.key90')/*优先取行驶里程*/, value: 'travel_priority' },
  { name: messages('expense-12.key91')/*参考/行驶里程中较大值*/, value: 'maximum' },
];

export const mileageRange = {
  'KM': { range: 50, reg: /[KM]+/g, name: messages('expense-12.key85')/*公里*/ },
  'MI': { range: 30, reg: /[MI]+/g, name: messages('expense-12.key86')/*英里*/ }
};

export const formData = {
  'name': {
    required: true,
    component: components.get('Input'),
    name: messages('expense-12.key92')/*规则名称*/
  },
  'enabled': {
    component: components.get('Switch'), name: messages('common.column.status')/*状态*/
  },
  'currency': {
    component: components.get('Selector'),
    name: messages('common.currency')/*币种*/,
    required: true,
    params: {
      type: 'currency',
      params: {
        getPopupContainer: triggerNode => triggerNode.parentNode,
        searchIfKeywordIsNull: true
      }
    }
  },
  'unitPrice': {
    name: messages('expense-12.key93')/*金额/里程单位*/,
    required: true,
    component: components.get('InputNumber'),
    params: {
      className: 'new-unit__input',
      placeholder: messages('expense-12.key94')/*请输入单价*/
    }
  },
  'ruleDesc': {
    name: messages('expense-12.key95')/*描述*/,
    required: true,
    component: components.get('TextArea'),
    params: {
      maxLength: 200,
      placeholder: messages('expense-12.key96')/*请输入，最多200个字符*/,
    }
  },
  'priority': {
    component: components.get('Priority'),
    params: {
      top: 'TENANT'
    }
  },
  'editable': {
    name: messages('expense-12.key97')/*途径信息修改*/,
    child: editableChild.map(item => <Radio value={item.value}>{item.name}</Radio>),
    extra: messages('expense-12.key98')/*配置里程补贴费用中是否允许修改出发到达途径的时间/地点信息*/,
    component: components.get('Group')
  },
  'manyInvoice': {
    name: messages('expense-12.key99')/*每月生成费用次数*/,
    child: manyInvoiceChild.map(item => <Radio value={item.value}>{item.name}</Radio>),
    extra: messages('expense-12.key100')/*可配置员工每人每月允许里程补贴汇总生成费用的次数*/,
    component: components.get('Group')
  },
  'stepMileage': {
    component: components.get('LadderMileage')
  },
  'userGroupVOs': {
    name: messages('expense-12.key101')/*适用人员*/,
    extra: messages('expense-12.key102')/*若为全部人员，则启用公司下的所有员工适用该规则；若为部分人员组，则人员组中为启用公司下的员工适用该规则*/,
    params: {
      type: 'user_group',
      options: [{ key: 1001, name: messages('common.all')/*全部*/ }, { key: 1002, name: messages('expense-12.key103')/*部分*/ }],
      valueKey: 'userGroupOID',
      labelKey: 'name'
    },
    required: true,
    component: components.get('MileagePriority'),
    initialValue: { select: 'all' }
  },
  'unitPriceRange': {
    name: messages('expense-12.key104')/*单价修改偏离率*/,
    extra: messages('expense-12.key105')/*配置员工是否可修改单价：修改后的单价偏离X%时，禁止生成费用，为0%则不允许修改，单价修改偏离率=（修改后的单价-参考单价）/ 参考单价 * 100%*/,
    params: {
      formatter: value => `${value}%`,
      parser: value => value.replace('%', ''),
      className: 'new-unit__input'
    },
    required: true,
    requireErrorMessage: messages('expense-12.key192')/*单价偏离率配置不可为空*/,
    component: components.get('InputNumber')
  },
  'defaultMileageValue': {
    name: messages('expense-12.key106')/*里程数默认值*/,
    child: defaultMileageValue.map(item => <Radio value={item.value}>{item.name}</Radio>),
    extra: <div>
      {messages('expense-12.key107')/*配置为“优先取行驶里程”时，若行驶里程为0，则里程数默认值取参考里程*/} <br/>
      {messages('expense-12.key108')/*当配置为“行驶里程”或“优先取行驶里程”时，由于行驶里程计算可能不准确，为避免员工无法创建里程，里程修改偏离率只可为空*/} <br/>
      {messages('expense-12.key109')/*钉钉以及企业微信端，由于没有行驶里程，无论此项如何配置，都默认为参考里程*/}
    </div>,
    component: components.get('Group')
  },
  'mileageModifyRange': {
    name: messages('expense-12.key110')/*里程修改偏离率*/,
    extra: messages('expense-12.key111')/*配置员工是否可修改里程：修改后的里程偏离X%时，禁止生成费用，为空则可随意修改，为0%则不允许修改里程修改偏离率=（修改后的里程-里程默认值）/ 里程默认值 * 100%*/,
    params: {
      formatter: value => value === '' ? value : `${value}%`,
      parser: value => value.replace('%', ''),
      className: 'new-unit__input'
    },
    component: components.get('InputNumber')
  },
  'addrModifyRange': {
    name: messages('expense-12.key112')/*地址修改范围*/,
    params: {
      min: 0,
      max: 50,
      step: 1,
      formatter: value => `${value}KM`,
      parser: value => value.replace(/[KM]+/g, ''),
      className: 'new-unit__input'
    },
    component: components.get('InputNumber')
  },
  'drivingPlanValue': {
    name: messages('expense-12.key113')/*参考里程计算策略*/,
    child: drivingPlanValueChild.map(item => <Radio value={item.value}>{item.name}</Radio>),
    extra: drivingExtra.map(item => (<span>{item}<br/></span>)),
    component: components.get('Group')
  },
  'mileageCreateModes': {
    name: messages('expense-12.key114')/*里程创建方式*/,
    required: true,
    requireErrorMessage: messages('expense-12.key115')/*请至少选择一个里程创建方式*/,
    child: mileageCreateModesValues.map(item => <Checkbox value={item.value}>{item.label}</Checkbox>),
    extra: messages('expense-12.key116')/*若客户使用企业微信/钉钉端，请务必开启定位创建，否则用户将无法创建里程*/,
    component: components.get('CheckboxGroup')
  },
  'mileageUnit': {
    name: messages('expense-12.key117')/*里程单位*/,
    child: mileageUnitChild.map(item => <Radio value={item.value}>{item.name}</Radio>),
    component: components.get('Group')
  },
};

export function DataProcessing(target) {
  return class extends target {
    searchData = {
      companyNameList: {
        id: 'companies',
        label: messages('expense-12.key118')/*启用公司*/,
        component: 'Chooser',
        props: {
          labelKey: 'name',
          valueKey: 'id',
          type: 'priority_company'
        },
        dataIndex: 'companyNameList',
        parser: value => ({
          companyIds: value ? value.map(item => item.id) : null
        })
      },
      enabled: {
        label: messages('common.column.status')/*状态*/,
        dataIndex: 'enabled',
        component: 'Switch',
        id: 'enabled',
        tagParser: value => value ? messages('expense-12.key119')/*启用temp*/ : messages('expense-12.key120')/*禁用temp*/
      },
    };
    columnsData = {
      stepVOs: {
        title: messages('expense-12.key121')/*阶梯里程*/,
        dataIndex: 'stepVOs',
        render: value => '0-' + value
          .map((item) => {
            return Object.values(item)[1] === '-1' ? '无限' : Object.values(item)[1];
          })
          .join('-')
      },
      ruleDesc: { title: messages('expense-12.key95')/*描述*/, dataIndex: 'ruleDesc' },
      currency: { title: messages('common.currency')/*币种*/, dataIndex: 'currency' },
      enabled: {
        title: messages('common.column.status')/*状态*/,
        dataIndex: 'enabled',
        render: enabled => (
          <Badge
            status={enabled ? 'success' : 'error'}
            text={enabled ? messages('expense-12.key119')/*启用temp*/ : messages('expense-12.key120')/*禁用temp*/}
          />
        )
      },
      operation: {
        title: messages('common.operation')/*操作*/,
        dataIndex: 'operation',
        render: (value, record) => (
          <Popconfirm
            onConfirm={() => this.handleDelete(record)}
            title={messages('expense-12.key122')/*确认删除？*/}
          >
            <Button disabled={this.isReadOnly() || record.readOnly} ghost type="link" onClick={(e) => e.stopPropagation()}>{messages('common.delete')/*删除*/}</Button>
          </Popconfirm>
        )
      },
      levelCode: {
        title: messages('expense-12.key123')/*层级*/,
        dataIndex: 'levelCode',
        render: (value) => levelCodeMap[value]
      },
      levelOrgName: { title: messages('expense-12.key124')/*所属组织*/, dataIndex: 'levelOrgName' },
      companyNameList: {
        title: messages('expense-12.key118')/*启用公司*/,
        dataIndex: 'companyNameList',
        render: value =>  value.join(',')
      },
      applicationUserGroupScope: {
        title: messages('expense-12.key101')/*适用人员*/,
        dataIndex: 'applicationUserGroupScope',
        render: (value, record) => {
          if (value === 1001) return messages('expense-12.key125')/*通用*/;
          return record.optionalUserGroup.map(item => item.name)
            .join(',');
        }
      },
    };

    handleColumns = (columns) => columns.map(column => {
      if ((/stepVOs.+/.test(column))) {
        return {
          title: column.replace(/stepVOs(.+)/, '$1'),
          dataIndex: column,
          render: (value, record) => {
            const middleValue = record.stepVOs.filter(item => item.startUnit === column.replace(/stepVOs(\d+)~(.+)/, '$1'))[0];
            return middleValue && middleValue.unitPrice ? middleValue.unitPrice : <span className="ladder-rule-detail__span">{messages('expense-12.key126')/*待补充*/}</span>;
          }
        };
      } else if (column === 'operationSpecial') {
        return {
          ...this.columnsData.operation,
          render: (value, record) => (
            <Popconfirm
              onConfirm={() => this.handleDelete(record)}
              title={messages('expense-12.key127')/*删除此阶梯里程，相关规则自动删除，确认删除？*/}
            >
              <Button disabled={this.isReadOnly() || record.readOnly} ghost type="link" onClick={(e) => e.stopPropagation()}>{messages('common.delete')/*删除*/}</Button>
            </Popconfirm>)
        };
      } else {
        return this.columnsData[column];
      }
    });

    handleSearchForm = (searchColumns) => searchColumns.map(searchColumn => this.searchData[searchColumn]);

    isReadOnly = () => {
      const { currentMenu } = this.props.currentMenuPermission;
      return !!(currentMenu && currentMenu.operationType !== 'RW');
    };
  };
}


